<?php defined('BASEPATH') OR exit('No direct script access allowed');


include_once(APPPATH.'libraries/MarketplaceWebService/Client.php');
include_once(APPPATH.'libraries/MarketplaceWebService/Exception.php');
define ('DATE_FORMAT', 'Y-m-d\TH:i:s\Z');
require APPPATH.'/libraries/REST_Controller.php';

class Feeds extends REST_Controller
{
	private $service;
	public $request;
	public $next_by_token = FALSE;
	
	function __construct()
	{
		// Construct our parent class
		parent::__construct();

		$serviceUrl = '';
		switch ($this->_merchant['region'])
		{
			case 'NA':
				$serviceUrl = "https://mws.amazonservices.com";
				break;

			case 'CA':
				$serviceUrl = "https://mws.amazonservices.ca";
				break;

			case 'DE':
				$serviceUrl = "https://mws.amazonservices.de";
				break;

			case 'FR':
				$serviceUrl = "https://mws.amazonservices.fr";
				break;

			case 'IT':
				$serviceUrl = "https://mws.amazonservices.it";
				break;

			case 'UK':
				$serviceUrl = "https://mws.amazonservices.co.uk";
				break;

			case 'JP':
				$serviceUrl = "https://mws.amazonservices.com.cn";
				break;

			case 'CN':
				$serviceUrl = "https://mws.amazonservices.com.cn";
				break;

			default:
				$serviceUrl = "https://mws.amazonservices.com";
			break;
		}

		$this->service = new MarketplaceWebService_Client(
		AWS_ACCESS_KEY_ID,
		AWS_SECRET_ACCESS_KEY,
		array (
                'ServiceURL' => $serviceUrl,
                'ProxyHost' => null,
                'ProxyPort' => -1,
                'MaxErrorRetry' => 3
		),
		APPLICATION_NAME,
		APPLICATION_VERSION
		);

		$tmp = $this->input->get('next_by_token');
		if($tmp)
		{
			$this->next_by_token = ((int)$tmp)?TRUE:FALSE;
		}
		
	}


	function submitFeed_post()
	{

		include_once(APPPATH.'libraries/MarketplaceWebService/Model/SubmitFeedRequest.php');
		$this->request = new MarketplaceWebService_Model_SubmitFeedRequest();

		$this->request->setMerchant(MERCHANT_ID);
		$marketplaceIdArray = array("Id" => array(MARKETPLACE_ID));
		$this->request->setMarketplaceIdList($marketplaceIdArray);

		$feed = '';
		if(count($_FILES))
		{
			$tmp = current($_FILES);
			if( isset($tmp['tmp_name']) )
			{
				$feed = file_get_contents($tmp['tmp_name']);
			}

		}
		$fname = $this->amazon_mws->create_file('feed');
		$feedHandle = @fopen($fname, 'rw+');
		fwrite($feedHandle, $feed);
		rewind($feedHandle);
		$this->request->setContentMd5(base64_encode(md5(stream_get_contents($feedHandle), true)));
		rewind($feedHandle);
		$this->request->setPurgeAndReplace(false);
		$this->request->setFeedContent($feedHandle);
		rewind($feedHandle);

		$params = array(
                    'FeedType' => array('type' => 'string')
		);
		$this->amazon_mws->set_request( $params, 'post');
		$this->invokeSubmitFeed($this->service, $this->request);


	}


	function invokeSubmitFeed(MarketplaceWebService_Interface $service, $request)
	{

		try
		{
			$response = $service->submitFeed($request);
			//echo $response->toXML();exit;
			$this->amazon_mws->format_output($response, 'GetReportRequestCountResult', 'GetReportRequestCountResult');
			$this->amazon_mws->show_ouput(TRUE);

		}
		catch (MarketplaceWebService_Exception $ex)
		{
			$this->amazon_mws->format_error($ex->getXML());
			$this->amazon_mws->show_ouput(FALSE);
		}

	}



	function getFeedSubmissionList_get()
	{
		include_once(APPPATH.'libraries/MarketplaceWebService/Model/GetFeedSubmissionListRequest.php');
		include_once(APPPATH.'libraries/MarketplaceWebService/Model/StatusList.php');
		$this->request = new MarketplaceWebService_Model_GetFeedSubmissionListRequest();
		$this->request->setMerchant(MERCHANT_ID);

		//$statusList = new MarketplaceWebService_Model_StatusList();
		//$this->request->setFeedProcessingStatusList($statusList->withStatus('_SUBMITTED_'));

		$params = array(
                    'MaxCount' => array('type' => 'string'),
                    'FeedSubmissionIdList' => array('type' => 'FeedSubmissionIdList'),
                    'FeedTypeList'         => array('type' => 'string'),
                    'FeedProcessingStatusList' => array('type' => 'FeedProcessingStatusList')

		);
		$this->amazon_mws->set_request( $params, 'get');

		$this->invokeGetFeedSubmissionList($this->service, $this->request);
	}
	
	function getFeedSubmissionListByNextToken_get()
	{
		include_once(APPPATH.'libraries/MarketplaceWebService/Model/GetFeedSubmissionListByNextTokenRequest.php');
		$this->request = new MarketplaceWebService_Model_GetFeedSubmissionListByNextTokenRequest();
		$this->request->setMerchant(MERCHANT_ID);
		$params = array(
			                    'NextToken' => array('type' => 'string')
		);
		$this->amazon_mws->set_request( $params, 'get');
		
		$this->invokeGetFeedSubmissionList($this->service, $this->request, 'next_token');
		
	}
	

	function invokeGetFeedSubmissionList(MarketplaceWebService_Interface $service, $request, $type = null)
	{

		try
		{
			$getFeedSubmissionList = 'getFeedSubmissionList';
			$isSetGetFeedSubmissionListResult = 'isSetGetFeedSubmissionListResult';
			$getGetFeedSubmissionListResult = 'getGetFeedSubmissionListResult';

			if(strcmp($type, 'next_token') === 0 )
			{
				$getFeedSubmissionList          = "getFeedSubmissionListByNextToken";
				$isSetGetFeedSubmissionListResult = 'isSetGetFeedSubmissionListByNextTokenResult';
				$getGetFeedSubmissionListResult = 'getGetFeedSubmissionListByNextTokenResult';
			}

			$response = $service->$getFeedSubmissionList($request);
			//echo $response->toXML();exit;
			$this->amazon_mws->format_output($response, ucfirst($getGetFeedSubmissionListResult).'|FeedSubmissionInfo', 'getGetFeedSubmissionListResult');

			//Get Next Token to fetch the next records in Queue
			$next_token = '';

			if ($response->$isSetGetFeedSubmissionListResult())
			{
				$getFeedSubmissionListResult = $response->$getGetFeedSubmissionListResult();

				if ($getFeedSubmissionListResult->isSetNextToken())
				{
					$next_token = $getFeedSubmissionListResult->getNextToken();
				}

			}

			$this->amazon_mws->next_token = $next_token;
			
			if( strcmp($next_token,'') !== 0 && $this->next_by_token )
			{
				include_once(APPPATH.'libraries/MarketplaceWebService/Model/GetFeedSubmissionListByNextTokenRequest.php');
				$this->request = new MarketplaceWebService_Model_GetFeedSubmissionListByNextTokenRequest();
				$this->request->setMerchant(MERCHANT_ID);
				$this->request->setNextToken($next_token);

				$this->invokeGetFeedSubmissionList($this->service, $this->request, 'next_token');
			}
			else
			{
				$this->amazon_mws->show_ouput(TRUE);
			}

		}
		catch (MarketplaceWebServiceOrders_Exception $ex)
		{
			$this->amazon_mws->format_error($ex->getXML());
			$this->amazon_mws->show_ouput(FALSE);
		}

	}


	function getFeedSubmissionResult_get()
	{
		include_once(APPPATH.'libraries/MarketplaceWebService/Model/GetFeedSubmissionResultRequest.php');
		$this->request = new MarketplaceWebService_Model_GetFeedSubmissionResultRequest();
		$this->request->setMerchant(MERCHANT_ID);
		$params = array(
                    'FeedSubmissionId' => array('type' => 'string')
		);
		$this->amazon_mws->set_request( $params, 'get');

		$FeedSubmissionId = '';
		if($this->request->isSetFeedSubmissionId())
		$FeedSubmissionId = $this->request->getFeedSubmissionId();

		$fname = $this->amazon_mws->create_file('feeds', $FeedSubmissionId);
		
		$this->request->setFeedSubmissionResult(@fopen($fname, 'rw+'));

			
		$this->invokeGetFeedSubmissionResult($this->service, $this->request);
	}


	function invokeGetFeedSubmissionResult(MarketplaceWebService_Interface $service, $request)
	{

		try
		{
			$response = $service->getFeedSubmissionResult($request);
			$this->amazon_mws->format_output($response, 'GetFeedSubmissionResult', 'GetFeedSubmissionResult');
			$this->amazon_mws->show_ouput(TRUE);

		}
		catch (MarketplaceWebService_Exception $ex)
		{
			$this->amazon_mws->format_error($ex->getXML());
			$this->amazon_mws->show_ouput(FALSE);
		}


	}

	
	function getFeedSubmissionCount_get()
	{
		include_once(APPPATH.'libraries/MarketplaceWebService/Model/GetFeedSubmissionCountRequest.php');
		$this->request = new MarketplaceWebService_Model_GetFeedSubmissionCountRequest();
		$this->request->setMerchant(MERCHANT_ID);
			
		$this->invokeGetFeedSubmissionCount($this->service, $this->request);
	}

	function invokeGetFeedSubmissionCount(MarketplaceWebService_Interface $service, $request)
	{

		try
		{
			$response = $service->getFeedSubmissionCount($request);
			$this->amazon_mws->format_output($response, 'GetFeedSubmissionCountResult', 'GetFeedSubmissionCountResult');
			$this->amazon_mws->show_ouput(TRUE);

		}
		catch (MarketplaceWebServiceOrders_Exception $ex)
		{
			$this->amazon_mws->format_error($ex->getXML());
			$this->amazon_mws->show_ouput(FALSE);
		}


	}


	function cancelFeedSubmissions_get()
	{
		include_once(APPPATH.'libraries/MarketplaceWebService/Model/CancelFeedSubmissionsRequest.php');
		$this->request = new MarketplaceWebService_Model_CancelFeedSubmissionsRequest();
		$this->request->setMerchant(MERCHANT_ID);

		$params = array(
                    'FeedSubmissionIdList' => array('type' => 'FeedSubmissionIdList')
		);
		$this->amazon_mws->set_request( $params, 'get');


		$this->invokeCancelFeedSubmissions($this->service, $this->request);
	}

	function invokeCancelFeedSubmissions(MarketplaceWebService_Interface $service, $request)
	{

		try
		{
			$response = $service->cancelFeedSubmissions($request);
			$this->amazon_mws->format_output($response, 'CancelFeedSubmissionsResult', 'CancelFeedSubmissionsResult');
			$this->amazon_mws->show_ouput(TRUE);

		}
		catch (MarketplaceWebServiceOrders_Exception $ex)
		{
			$this->amazon_mws->format_error($ex->getXML());
			$this->amazon_mws->show_ouput(FALSE);
		}


	}




}
